// lib/controllers/settings/settings_controller.dart
import 'package:get/get.dart';
import 'package:drift/drift.dart' as drift;

import '../../../data/datasource/local/database.dart';


import '../../../core/network/bao_stock_service.dart';
import '../../../data/datasource/local/database.dart' as drift;
import '../../../data/datasource/local/database_manager.dart';

class SettingsController extends GetxController {
  final BaoStockService _baoStockService = BaoStockService();

  final AppDatabase _database;

  SettingsController() : _database = DatabaseManager.instance;



  // 状态变量
  var isImporting = false.obs;
  var importProgress = 0.0.obs;
  var importStatus = ''.obs;
  var stockCount = 0.obs;

  @override
  void onInit() {
    super.onInit();
    _loadStockCount();
  }

  // 加载股票数量
  Future<void> _loadStockCount() async {
    try {
      final count = await _database.getStockCount();
      stockCount.value = count;
    } catch (e) {
      print('加载股票数量失败: $e');
    }
  }

  // 导入股票代码
  Future<void> importStockCodes() async {
    if (isImporting.value) return;

    isImporting.value = true;
    importStatus.value = '正在连接Baostock服务器...';
    importProgress.value = 0.0;

    importStatus.value = '正在下载股票代码...';
    final stockCodes = await _baoStockService.getAllStocks();
    print('获取到 ${stockCodes.length} 只股票代码');

// 输出前10个代码作为样本
    if (stockCodes.isNotEmpty) {
      print('样本代码: ${stockCodes.take(10).toList()}');
    }

// 过滤无效代码
    final validCodes = stockCodes.where((code) => _isValidStockCode(code)).toList();
    print('有效股票代码: ${validCodes.length} 只');





    try {
      // 登录Baostock
      importStatus.value = '正在登录Baostock...';
      final loginSuccess = await _baoStockService.login();

      if (!loginSuccess) {
        importStatus.value = '登录Baostock失败，请检查网络连接';
        isImporting.value = false;
        return;
      }

      // 获取所有股票代码
      importStatus.value = '正在下载股票代码...';
      final stockCodes = await _baoStockService.getAllStocks();

      if (stockCodes.isEmpty) {
        importStatus.value = '未获取到股票代码';
        isImporting.value = false;
        return;
      }

      // 清空现有数据
      await _clearStockCodes();

      // 分批处理股票代码，避免内存溢出
      const batchSize = 50; // 减小批次大小以减少内存压力
      final total = stockCodes.length;

      for (var i = 0; i < total; i += batchSize) {
        final end = i + batchSize > total ? total : i + batchSize;
        final batch = stockCodes.sublist(i, end);

        // 更新进度
        final progress = (i / total).clamp(0.0, 1.0);
        importProgress.value = progress;
        importStatus.value = '正在处理股票数据 (${(progress * 100).toStringAsFixed(1)}%)...';

        // 处理当前批次
        await _processStockBatch(batch);

        // 稍微延迟，避免请求过于频繁
        await Future.delayed(const Duration(milliseconds: 200));
      }

      // 更新最终进度
      importProgress.value = 1.0;

      // 更新股票数量
      await _loadStockCount();

      importStatus.value = '导入成功！共导入 ${stockCodes.length} 只股票';
    } catch (e) {
      print('导入股票代码失败: $e');
      importStatus.value = '导入失败: $e';
    } finally {
      isImporting.value = false;
    }
  }

  // 处理股票批次
  Future<void> _processStockBatch(List<String> stockCodes) async {
    try {
      final companions = <drift.StockCodesCompanion>[];

      for (final code in stockCodes) {


        try {
          if (!_isValidStockCode(code)) {
            print('跳过无效股票代码: $code');
            continue;
          }
          // 获取股票基本信息
          final basicInfoList = await _baoStockService.getStockBasic(code);

          if (basicInfoList.isNotEmpty) {
            final basicInfo = basicInfoList.first;

            // 解析上市日期
            DateTime? listingDate;
            if (basicInfo.ipoDate.isNotEmpty) {
              try {
                listingDate = DateTime.parse(basicInfo.ipoDate);
              } catch (e) {
                print('解析上市日期失败: ${basicInfo.ipoDate}');
              }
            }

            // 创建Companion对象
            final companion = _database.createStockCodeCompanion(
              code,
              name: basicInfo.codeName,
              listingDate: listingDate,
              securityType: 1, // 默认为股票
              listingStatus: 1, // 默认为上市状态
            );

            companions.add(companion);
          } else {
            // 即使获取基本信息失败，也保存股票代码
            final companion = _database.createStockCodeCompanion(code);
            companions.add(companion);
          }
        } catch (e) {
          print('获取股票 $code 信息失败: $e');
          // 即使获取基本信息失败，也保存股票代码
          final companion = _database.createStockCodeCompanion(code);
          companions.add(companion);
        }
      }

      // 批量插入数据库
      if (companions.isNotEmpty) {
        await _database.batchInsertStockCodes(companions);
      }
    } catch (e) {
      print('处理股票批次失败: $e');
      // 不重新抛出异常，继续处理下一批次
    }
  }

  // 添加股票代码验证方法
  bool _isValidStockCode(String code) {
    // 检查代码格式：sh.XXXXXX 或 sz.XXXXXX，其中X是数字
    final pattern = RegExp(r'^(sh|sz)\.\d{6}$');
    if (!pattern.hasMatch(code)) {
      return false;
    }

    // 排除指数代码（如sz.399）
    if (code.startsWith("sz.399")) {
      return false;
    }

    return true;
  }


  // 清空股票代码表
  Future<void> _clearStockCodes() async {
    try {
      // 使用更高效的方式清空表
      await _database.customStatement('DELETE FROM stock_codes');
    } catch (e) {
      print('清空股票代码表失败: $e');
      rethrow;
    }
  }

  // 清空数据库
  Future<void> clearDatabase() async {
    try {
      await _clearStockCodes();
      await _loadStockCount();
      Get.snackbar('成功', '数据库已清空', snackPosition: SnackPosition.BOTTOM);
    } catch (e) {
      print('清空数据库失败: $e');
      Get.snackbar('错误', '清空数据库失败: $e', snackPosition: SnackPosition.BOTTOM);
    }
  }
}